package com.mmall.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mmall.concurrency.example.atomic.AtomicExample3;

@Slf4j
public class CyclicBarrierExample2 {
	private static Logger log = LoggerFactory.getLogger(AtomicExample3.class);

    private static CyclicBarrier barrier = new CyclicBarrier(5); // 一起同步等待的线程数

    public static void main(String[] args) throws Exception {

        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0; i < 10; i++){
            final int threadNum = i;
            Thread.sleep(1000);
            executorService.execute(()->{
                try{
                    race(threadNum);
                }catch (Exception e){
                    log.error("exception", e);
                }
            });
        }
        executorService.shutdown();
    }

    private static void race(int threadNum) throws Exception{
        Thread.sleep(1000);
        log.info("{} is ready.", threadNum);
        try{
            barrier.await(2000, TimeUnit.MILLISECONDS); // 等待2000毫秒, 然后直接结束等待，会让下面的执行抛出异常
        }catch (BrokenBarrierException | TimeoutException e){
            log.warn("BarrierException", e);
        }
        log.info("{} continue", threadNum);
    }
}

/*
执行结果如下：


* */